package com.aitou.mrylive.presentation.ui.main.me;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.facebook.binaryresource.FileBinaryResource;
import com.facebook.cache.common.SimpleCacheKey;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.view.SimpleDraweeView;
import com.jakewharton.rxbinding.view.RxView;
import com.aitou.mrylive.R;
import com.aitou.mrylive.data.bean.HotAnchorSummary;
import com.aitou.mrylive.data.bean.me.PlayBackInfo;
import com.aitou.mrylive.data.bean.me.UserInfo;
import com.aitou.mrylive.data.repository.SourceFactory;
import com.aitou.mrylive.domain.LocalDataManager;
import com.aitou.mrylive.presentation.ui.base.BaseActivity;
import com.aitou.mrylive.presentation.ui.chatting.ChatActivity;
import com.aitou.mrylive.presentation.ui.main.currency.CurrencyActivity;
import com.aitou.mrylive.presentation.ui.room.RoomActivity;
import com.aitou.mrylive.presentation.ui.room.player.PlayerFragment;
import com.aitou.mrylive.util.Const;
import com.aitou.mrylive.util.FrescoUtil;
import com.aitou.mrylive.util.L;
import com.aitou.mrylive.util.PicUtil;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.api.BasicCallback;
import rx.functions.Action1;

//用户主页
public class OtherUserActivity extends BaseActivity implements IMe{
    private static String KEY_ID = "id";
    private static String KEY_SHOW_ONLINE = "showOnline";
    private String mUid = "";
    private static final String TARGET_ID = "targetId";
    private boolean isCanShowOnline = false;
    private ViewPager mViewPager;
    private ImageButton mBack;
    private TextView mOnline;
    private TextView mName, mId, mSign, mSent;
    private SimpleDraweeView mPhoto;
    private ImageView mSex, mEdit;
    //    下面三个按钮  关注私聊 拉黑
    private LinearLayout mStarBtn,mChatBtn,mPullBackBtn;
    //    拉黑的文字
    private TextView mPullBackTv;
    private TextView mStarTv;
    private TextView mStar, mFans,mDataTab,mBackPlayTab;
    private ImageView mlevel;
    //    下面的是关注  粉丝
    private View mStarLine,mFansLine;
    private MePresenter mPresenter;
    private TextView mRank;
    private UserInfo mUserInfo;
    private Context mContext;
    private boolean r=false;
    private boolean f=false;
    private boolean m=false;
    private String id;
    private Bitmap bitmap;

    private HotAnchorSummary hotAnchorSummary;

    //使用列表存放，方便遍历
    private List<SimpleDraweeView> topContributeDrawees;

    public static Intent createIntent(Context context,int uid,boolean showOnline) {
        Intent intent = new Intent(context, OtherUserActivity.class);
        intent.putExtra(KEY_ID ,uid);
        intent.putExtra(KEY_SHOW_ONLINE,showOnline);
        return intent;
    }

    @Override
    protected void onResume() {
//        MobclickAgent.onPageStart("用户主页");
        super.onResume();
        mPresenter.loadUserInfo(Integer.parseInt(mUid));
    }

    @Override
    protected void onPause() {
//        MobclickAgent.onPageEnd("用户主页");
        super.onPause();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_otheruser;
    }

    @Override
    protected void findViews(Bundle savedInstanceState) {
        mUid = String.valueOf( this.getIntent().getIntExtra(KEY_ID,0));
        mContext=this;
        isCanShowOnline = this.getIntent().getBooleanExtra(KEY_SHOW_ONLINE,false);
        mViewPager = $(R.id.other_user_viewpager);
        mBack = (ImageButton) findViewById(R.id.imgbtn_toolbar_back);
        mOnline = (TextView) findViewById(R.id.me_massage);

        mPhoto = $(R.id.me_photo);
//        mMinPhoto = $(R.id.me_photo_min);

        mName = $(R.id.me_name);
        mSign = $(R.id.me_sign);
        mSent = $(R.id.me_send);
        mSex = $(R.id.me_sex);
        mEdit = $(R.id.me_edit);
        mId = $(R.id.me_id);
        mStar = $(R.id.me_user_info_star);
        mDataTab=$(R.id.me_user_info_data_tab);
        mFans = $(R.id.me_user_info_fans);
        mBackPlayTab=$(R.id.me_user_info_backplay_tab);
        mlevel=$(R.id.other_level);


        mStarBtn = $(R.id.other_user_starly);
        mChatBtn=$(R.id.other_user_letter);
        mPullBackBtn=$(R.id.other_user_pull_black);
        mStarTv = $(R.id.other_user_star);
        mPullBackTv=$(R.id.other_user_pull_black_tv);

        mStarLine = $(R.id.other_user_star_line);
        mFansLine = $(R.id.other_user_fans_line);

        mRank = $(R.id.me_coin_rank_tv);

        topContributeDrawees = new ArrayList<>();
        SimpleDraweeView draweeTop1 = $(R.id.me_coin_top1);
        SimpleDraweeView draweeTop2 = $(R.id.me_coin_top2);
        SimpleDraweeView draweeTop3 = $(R.id.me_coin_top3);
        topContributeDrawees.add(draweeTop1);
        topContributeDrawees.add(draweeTop2);
        topContributeDrawees.add(draweeTop3);

    }

    @Override
    protected void init() {
        mPresenter = new MePresenter(this);
        mStarBtn.setVisibility(View.VISIBLE);
        TextView tvRankLabel = $(R.id.me_coin_rank_tv);
        tvRankLabel.setText(getString(R.string.coin_rank, getString(R.string.app_currency)));

        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mEdit.setVisibility(View.GONE);
        mDataTab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mViewPager.setCurrentItem(0);
            }
        });
        mBackPlayTab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mViewPager.setCurrentItem(1);
            }
        });

        RxView.clicks(mRank).throttleFirst(Const.VIEW_THROTTLE_TIME, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        if (mUserInfo != null) {
                            startActivity(CurrencyActivity.createIntent(OtherUserActivity.this,
                                    mUserInfo.getId(),
                                    mUserInfo.getCoinBalance()));
                        }
                    }
                });



        mViewPager.setCurrentItem(0);
        setCheck(0);
    }

    private void setCheck(int position){
        if(position == 0){
//            mStar.setTextColor(getResources().getColor(R.color.yunkacolor));
            mStarLine.setVisibility(View.VISIBLE);
//            mFans.setTextColor(getResources().getColor(R.color.rgb_AAAAAA));
            mFansLine.setVisibility(View.INVISIBLE);
        }else{
//            mStar.setTextColor(getResources().getColor(R.color.rgb_AAAAAA));
            mStarLine.setVisibility(View.INVISIBLE);
//            mFans.setTextColor(getResources().getColor(R.color.yunkacolor));
            mFansLine.setVisibility(View.VISIBLE);
        }
    }
    private void starUser(){
        if (mUid!=null) {
            mPresenter.starUser(LocalDataManager.getInstance().getLoginInfo().getToken(),mUid,"");
        }
//        mStarTv.setText(getResources().getString(R.string.is_star));
//        mStarBtn.setTag(1);
    }

    private void unStarUser(){
        if (mUid!=null) {
            mPresenter.unStarUser(LocalDataManager.getInstance().getLoginInfo().getToken(),mUid,"");
        }
//        mStarTv.setText(getResources().getString(R.string.star));
//        mStarBtn.setTag(0);
    }
    @Override
    public void showInfo( UserInfo info) {
        if (info == null) {
            return;
        }
        mUserInfo = info;
        if (info.getSnap() != null) {
            FrescoUtil.frescoResize(
                    SourceFactory.wrapPathToUri(info.getSnap()),
                    getWidth(),
                    getWidth(),
                    mPhoto
            );
        }
        //获取当前头像bitmap值
//        Glide.with(mContext).load(SourceFactory.wrapPathToUri(info.getSnap())).asBitmap().into(new SimpleTarget<Bitmap>() {
//            @Override
//            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
//                bitmap=resource;
//            }
//        });
//        bitmap =returnBitmap(SourceFactory.wrapPathToUri(info.getSnap()));
        //TODO add min photo
        if (info.getNickname() != null) {
            mName.setText(info.getNickname());
        }
        mSex.setImageResource(info.getSex() == 0 ? R.drawable.ic_male : R.drawable.ic_female);

        if (info.getIntro() != null) {
            mSign.setText(info.getIntro());
        }
        if (info.getLevel() != null) {
            mlevel.setImageResource(PicUtil.getLevelImageId(this,Integer.parseInt(info.getLevel())));
        }
//        mId.setText("");
//        PicUtil.TextViewSpandImg(this,mId,R.drawable.ic_me_renzheng
//                ,R.dimen.city_height,R.dimen.city_height);
//        mId.append(this.getResources().getString(R.string.userinfo_dialog_certification));

        if (info.getTotalContribution() != 0) {
            mSent.setText("送出  " + info.getTotalContribution());
        }

        //贡献榜前三的头像
        List<String> topAvatars = info.getTopContributeUsers();
        if (topAvatars!=null){
            int avatarSize = (int) getResources().getDimension(R.dimen.avatar_size_default);
            //取可显示的头像个数和返回的头像个数的较小值执行遍历
            for (int i=0; i< Math.min(topContributeDrawees.size(), topAvatars.size()); i++){
                FrescoUtil.frescoResize(SourceFactory.wrapPathToUri(topAvatars.get(i)),
                        avatarSize, avatarSize, topContributeDrawees.get(i));
            }
        }

        mStar.setText(getString(R.string.my_info_follower_count, info.getFolloweesCount()));
        mFans.setText(getString(R.string.my_info_followee_count, info.getFollowersCount()));

        Log.i("mrl",info.getIsAttention()+"初始化关注"+info.getNickname()+info.toString());
        if(info.getIsAttention()==1){
            mStarTv.setText(getResources().getString(R.string.is_star));
            mStarBtn.setTag(1);
        }else{
            mStarTv.setText(getResources().getString(R.string.star));
            mStarBtn.setTag(0);
        }

//        关注
        mStarBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(Integer.parseInt(mStarBtn.getTag().toString()) == 1){
                    unStarUser();
                }else{
                    starUser();
                }
            }
        });

//        拉黑
        mPullBackBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                没被拉黑
                if (mUserInfo.getIsHit()==0) {
                    mPresenter.setHit(LocalDataManager.getInstance().getLoginInfo().getToken(), mUserInfo.getId());
                }else {
                    mPresenter.removeHit(LocalDataManager.getInstance().getLoginInfo().getToken(), mUserInfo.getId());
                }
            }
        });

//        私信
        mChatBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                id="meilibo"+mUserInfo.getId();
                if (mUserInfo!=null) {
                    for (int i = 0; i < 5; i++) {
                        L.e("lw", "注册操作" + i);
                        JMessageClient.register(id, id, new BasicCallback() {
                            @Override
                            public void gotResult(int status, String desc) {
                                if (status == 0) {
                                    L.e("lw","注册成功");
                                    m=true;
                                } else {
                                    L.e("lw", "注册失败" + status + desc);
                                    if (desc.equals("user exist")) {
                                        m=true;
                                    }
                                }
                            }
                        });
                        if (m = true) {
                            break;
                        }
                    }

                    if (JMessageClient.getMyInfo() == null) {
                        final String mMyName = "meilibo"+LocalDataManager.getInstance().getLoginInfo().getUserId();
                        final String mMyPassword = "meilibo"+LocalDataManager.getInstance().getLoginInfo().getUserId();
                        for (int i = 0; i < 5; i++) {
                            L.e("lw", "注册操作" + i);
                            JMessageClient.register(mMyName, mMyPassword, new BasicCallback() {
                                @Override
                                public void gotResult(int status, String desc) {
                                    if (status == 0) {
                                        r=true;
                                    } else {
                                        L.i("lw","注册失败"+status+"+"+"可能用户名存在");
                                        if (desc.equals("user exist")) {
                                            r=true;
                                        }
                                    }
                                }
                            });
                            if (r = true) {
                                break;
                            }
                        }
                        if (r=true) {
                            for (int j = 0; j < 5; j++) {
                                L.e("lw", "登录操作" + j);
                                JMessageClient.login(mMyName, mMyPassword, new BasicCallback() {
                                    @Override
                                    public void gotResult(int status, String desc) {
                                        if (status == 0) {
                                            f=true;
                                            Intent intent = new Intent();
                                            intent.putExtra(TARGET_ID, id);
                                            intent.putExtra("name", mUserInfo.getNickname());
//                                            intent.putExtra("fromimg",bitmap);
                                            intent.putExtra("t","2");
                                            intent.setClass(mContext, ChatActivity.class);
                                            startActivity(intent);
                                        } else {
                                            toastShort("网络不稳定，请稍后");
                                        }
                                    }
                                });
                                if (f = true) {
                                    break;
                                }
                            }
                        }
                    }else {
                        Intent intent = new Intent();
                        L.e("lw", "登录操作" + bitmap);
//                        intent.putExtra("fromimg",bitmap);
                        intent.putExtra(TARGET_ID, id);
                        L.e("lw", "登录操作" + id);
                        intent.putExtra("t","2");
                        intent.putExtra("name", mUserInfo.getNickname());
                        intent.setClass(mContext, ChatActivity.class);
                        startActivity(intent);
                    }
                }
            }
        });
        if (info.getIsHit()==1) {
            mPullBackTv.setText("已被拉黑");
        }else {
            mPullBackTv.setText("拉黑");
        }

        if(isCanShowOnline&&(!TextUtils.isEmpty(info.getBroadcasting()))&&info.getBroadcasting().equals("y")){
            mOnline.setVisibility(View.VISIBLE);
            hotAnchorSummary = new HotAnchorSummary();
            hotAnchorSummary.setAvatar(info.getAvatar());
            hotAnchorSummary.setCurrentRoomNum(info.getCurrentRoomNum());
            hotAnchorSummary.setId(info.getId());
            hotAnchorSummary.setNickname(info.getNickname());
            hotAnchorSummary.setOnlineCount(0);
            mOnline.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    intentRoom();
                }
            });
        }

        OtherUserBackPlayFragment otherUserBackPlayFragment=OtherUserBackPlayFragment.newInstance(mUserInfo);
        otherUserBackPlayFragment.setOtherUserActivity(this);

        final Fragment[] fragments = new Fragment[]{OtherUserDataFragment.newInstance(mUserInfo),
                otherUserBackPlayFragment};
        mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragments[position];
            }

            @Override
            public int getCount() {
                return fragments.length;
            }
        });
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                setCheck(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void getPlayLists(List<PlayBackInfo> playBackList) {

    }

    @Override
    public void getPlayUrl(String url) {

    }

    //    拉黑回调
    @Override
    public void getHitCode(int code) {
        if (code==0) {
            toastShort("成功拉黑");
            mUserInfo.setIsHit(1);
            mPullBackTv.setText("已被拉黑");
            mStarTv.setText(getResources().getString(R.string.star));
            mStarBtn.setTag(0);
        }
    }

    @Override
    public void getRemoveHitCode(int code) {
        if (code==0) {
            toastShort("成功解除拉黑");
            mUserInfo.setIsHit(0);
            mPullBackTv.setText("拉黑");
        }
    }


    @Override
    public void getStartCode(int code) {
        if (code==0) {
            toastShort("成功关注");
            mStarTv.setText(getResources().getString(R.string.is_star));
            mStarBtn.setTag(1);
            mUserInfo.setIsHit(0);
            mPullBackTv.setText("拉黑");
        }
    }

    @Override
    public void getRemoveStartCode(int code) {
        if (code==0) {
            toastShort("成功解除关注");
            mStarTv.setText(getResources().getString(R.string.star));
            mStarBtn.setTag(0);
        }
    }

    private void intentRoom(){
        Intent i = RoomActivity.createIntent(this,RoomActivity.TYPE_VIEW_LIVE, hotAnchorSummary
                .getCurrentRoomNum(), hotAnchorSummary.getId(), PlayerFragment
                .createArgs(hotAnchorSummary));
        startActivity(i);
    }
    private Bitmap returnBitmap(Uri uri) {

        Bitmap bitmap = null;
        FileBinaryResource resource = (FileBinaryResource) Fresco.getImagePipelineFactory().getMainDiskStorageCache().getResource(new SimpleCacheKey(uri.toString()));
        File file = resource.getFile();
        bitmap = BitmapFactory.decodeFile(file.getPath());
        return bitmap;

    }
}
